import Request from "./requests";
import { mergeProps } from "../utils";
import LsObj from "../core/ls";
import 'element-plus/es/components/message/style/css'
import 'element-plus/es/components/notification/style/css'
import { ElMessage } from "element-plus";

// 登录标志位
let goLogining = false
let token = null

const ResponseCode = {
  success: "200", // 正常返回
  failCode: ['401'],
};

async function interceptorRequest(req) {
  if (!token) {
    token = LsObj.common.token.get()
  }
  const defaultHeader = {
    "Content-Type": "application/json;charset=UTF-8"
  };
  req.headers = mergeProps(defaultHeader, req.headers);
  return req;
}

function interceptorResponse(res, config) {
  const { data } = res;
  const statusInfo = data.statusInfo;
  if (!statusInfo) {
    ElMessage("system error");
    return {
      error: "system error",
    };
  }
  if (statusInfo.code === ResponseCode.success) {
    if (config.showSuccessMessage === true) {
      ElMessage({
        message: config.successMsg || statusInfo.message,
        type: "success",
        grouping: true,
      });
    }
    return {
      result: data,
    };
  } else if (ResponseCode.failCode.includes(statusInfo.code)) {
    goLogining = true;
  }
  if (config.showFailedMessage !== false) {
    ElMessage.closeAll()
    ElMessage({
      message: config.errorMsg || data.statusInfo.message,
      type: "error",
      grouping: true,
    });
  }
  return {
    error: data,
  };
}

function errorHandler(error) {
  console.error(error);
  return {
    error,
  };
}

async function request(requestConfig = {}, config) {
  const instance = new Request({
    timeout: 60 * 1000,
    baseURL: process.env.VUE_APP_BASE_API,
    ...requestConfig,
  });
  const _config = mergeProps(
    {
      showFailedMessage: true,
      showSuccessMessage: false,
    },
    config
  );
  instance.interceptorsRequest((req) => {
    return interceptorRequest(req, _config);
  }, errorHandler);
  instance.interceptorsResponse((res) => {
    return interceptorResponse(res, _config);
  }, errorHandler);
  return instance.send();
}

export default request;
